<template>
  <Layout>
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 标题和标签切换 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b">
          <h1 class="text-2xl font-bold text-gray-900">关注与粉丝</h1>
        </div>

        <!-- 标签切换 -->
        <div class="border-b">
          <nav class="flex -mb-px">
            <button
              @click="activeTab = 'following'"
              class="px-6 py-3 border-b-2 font-medium text-sm transition-colors"
              :class="activeTab === 'following'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
            >
              关注 ({{ stats.following_count }})
            </button>
            <button
              @click="activeTab = 'followers'"
              class="px-6 py-3 border-b-2 font-medium text-sm transition-colors"
              :class="activeTab === 'followers'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
            >
              粉丝 ({{ stats.followers_count }})
            </button>
            <button
              @click="activeTab = 'mutual'"
              class="px-6 py-3 border-b-2 font-medium text-sm transition-colors"
              :class="activeTab === 'mutual'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
            >
              互相关注 ({{ stats.mutual_count }})
            </button>
          </nav>
        </div>

        <!-- 搜索栏 -->
        <div class="p-4 bg-gray-50">
          <div class="relative">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索用户..."
              class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            />
            <svg class="absolute left-3 top-2.5 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
        </div>

        <!-- 用户列表 -->
        <div class="p-6">
          <div v-if="loading" class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>

          <div v-else-if="filteredUsers.length === 0" class="text-center py-8">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            <p class="mt-2 text-gray-500">
              {{ activeTab === 'following' ? '还没有关注任何人' : activeTab === 'followers' ? '还没有粉丝' : '还没有互相关注的用户' }}
            </p>
          </div>

          <div v-else class="space-y-4">
            <div
              v-for="user in paginatedUsers"
              :key="user.id"
              class="flex items-start justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
            >
              <div class="flex items-start space-x-4">
                <!-- 头像 -->
                <Link :href="`/profile/${user.username}`">
                  <img
                    :src="user.avatar || `https://ui-avatars.com/api/?name=${user.name}&size=100`"
                    :alt="user.name"
                    class="w-12 h-12 rounded-full hover:opacity-90"
                  />
                </Link>

                <!-- 用户信息 -->
                <div class="flex-1">
                  <div class="flex items-center space-x-2">
                    <Link
                      :href="`/profile/${user.username}`"
                      class="font-semibold text-gray-900 hover:text-blue-600"
                    >
                      {{ user.name }}
                    </Link>
                    <span v-if="user.is_verified" class="text-blue-500" title="认证用户">
                      <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                      </svg>
                    </span>
                    <span v-if="user.is_mutual" class="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
                      互相关注
                    </span>
                  </div>
                  <p class="text-sm text-gray-500">@{{ user.username }}</p>
                  <p v-if="user.bio" class="mt-1 text-sm text-gray-600">{{ user.bio }}</p>

                  <!-- 用户统计 -->
                  <div class="mt-2 flex items-center space-x-4 text-sm text-gray-500">
                    <span>{{ user.posts_count }} 文章</span>
                    <span>{{ user.followers_count }} 粉丝</span>
                    <span>{{ user.following_count }} 关注</span>
                  </div>

                  <!-- 共同关注 -->
                  <div v-if="user.mutual_follows?.length > 0" class="mt-2 flex items-center">
                    <div class="flex -space-x-2">
                      <img
                        v-for="mutual in user.mutual_follows.slice(0, 3)"
                        :key="mutual.id"
                        :src="mutual.avatar || `https://ui-avatars.com/api/?name=${mutual.name}&size=50`"
                        :alt="mutual.name"
                        :title="mutual.name"
                        class="w-6 h-6 rounded-full ring-2 ring-white"
                      />
                    </div>
                    <span class="ml-2 text-xs text-gray-500">
                      {{ user.mutual_follows.length > 3 ? `等${user.mutual_follows.length}位` : '' }}共同关注
                    </span>
                  </div>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="ml-4 flex-shrink-0">
                <button
                  v-if="activeTab === 'following' || (activeTab === 'mutual' && user.is_following)"
                  @click="unfollow(user)"
                  class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm font-medium"
                >
                  取消关注
                </button>
                <button
                  v-else-if="activeTab === 'followers' && !user.is_following"
                  @click="follow(user)"
                  class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm font-medium"
                >
                  关注
                </button>
                <button
                  v-else-if="user.is_following"
                  @click="unfollow(user)"
                  class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm font-medium"
                >
                  已关注
                </button>
                <button
                  v-else
                  @click="follow(user)"
                  class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm font-medium"
                >
                  回关
                </button>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="mt-6 flex justify-center">
            <nav class="flex space-x-2">
              <button
                @click="currentPage--"
                :disabled="currentPage === 1"
                class="px-3 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上一页
              </button>

              <button
                v-for="page in visiblePages"
                :key="page"
                @click="currentPage = page"
                class="px-3 py-2 rounded-md text-sm font-medium"
                :class="currentPage === page
                  ? 'bg-blue-600 text-white'
                  : 'border border-gray-300 text-gray-700 hover:bg-gray-50'"
              >
                {{ page }}
              </button>

              <button
                @click="currentPage++"
                :disabled="currentPage === totalPages"
                class="px-3 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </nav>
          </div>
        </div>
      </div>

      <!-- 推荐用户 -->
      <div class="mt-6 bg-white rounded-lg shadow-md p-6">
        <h2 class="text-lg font-semibold mb-4">推荐关注</h2>

        <div v-if="recommendations.length === 0" class="text-center py-4 text-gray-500">
          暂无推荐
        </div>

        <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div
            v-for="user in recommendations"
            :key="user.id"
            class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
          >
            <div class="flex items-center space-x-3">
              <Link :href="`/profile/${user.username}`">
                <img
                  :src="user.avatar || `https://ui-avatars.com/api/?name=${user.name}&size=80`"
                  :alt="user.name"
                  class="w-10 h-10 rounded-full"
                />
              </Link>
              <div>
                <Link
                  :href="`/profile/${user.username}`"
                  class="font-medium text-gray-900 hover:text-blue-600"
                >
                  {{ user.name }}
                </Link>
                <p class="text-sm text-gray-500">{{ user.followers_count }} 粉丝</p>
              </div>
            </div>
            <button
              @click="follow(user)"
              class="px-3 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm"
            >
              关注
            </button>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Link } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'

const loading = ref(false)
const activeTab = ref('following')
const searchQuery = ref('')
const currentPage = ref(1)
const perPage = 20

const following = ref([])
const followers = ref([])
const recommendations = ref([])

const stats = ref({
  following_count: 0,
  followers_count: 0,
  mutual_count: 0
})

// 当前标签的用户列表
const currentUsers = computed(() => {
  if (activeTab.value === 'following') {
    return following.value
  } else if (activeTab.value === 'followers') {
    return followers.value
  } else {
    // 互相关注
    return following.value.filter(u => u.is_mutual)
  }
})

// 过滤后的用户
const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return currentUsers.value
  }

  const query = searchQuery.value.toLowerCase()
  return currentUsers.value.filter(user =>
    user.name.toLowerCase().includes(query) ||
    user.username.toLowerCase().includes(query) ||
    (user.bio && user.bio.toLowerCase().includes(query))
  )
})

// 分页后的用户
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * perPage
  const end = start + perPage
  return filteredUsers.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredUsers.value.length / perPage)
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

const loadFollowing = async () => {
  try {
    const response = await axios.get('/api/user/following')
    following.value = response.data
  } catch (error) {
    console.error('加载关注列表失败:', error)
  }
}

const loadFollowers = async () => {
  try {
    const response = await axios.get('/api/user/followers')
    followers.value = response.data
  } catch (error) {
    console.error('加载粉丝列表失败:', error)
  }
}

const loadRecommendations = async () => {
  try {
    const response = await axios.get('/api/user/recommendations')
    recommendations.value = response.data
  } catch (error) {
    console.error('加载推荐用户失败:', error)
  }
}

const loadStats = async () => {
  try {
    const response = await axios.get('/api/user/follow-stats')
    stats.value = response.data
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const follow = async (user) => {
  try {
    await axios.post(`/api/follow/${user.id}`)
    user.is_following = true
    user.followers_count++

    // 更新统计
    stats.value.following_count++
    if (user.is_follower) {
      user.is_mutual = true
      stats.value.mutual_count++
    }

    // 从推荐列表中移除
    const index = recommendations.value.findIndex(u => u.id === user.id)
    if (index > -1) {
      recommendations.value.splice(index, 1)
    }
  } catch (error) {
    console.error('关注失败:', error)
  }
}

const unfollow = async (user) => {
  if (!confirm(`确定要取消关注 ${user.name} 吗？`)) return

  try {
    await axios.delete(`/api/follow/${user.id}`)
    user.is_following = false
    user.followers_count--

    // 更新统计
    stats.value.following_count--
    if (user.is_mutual) {
      user.is_mutual = false
      stats.value.mutual_count--
    }

    // 如果在关注列表中，直接移除
    if (activeTab.value === 'following' || activeTab.value === 'mutual') {
      const index = following.value.findIndex(u => u.id === user.id)
      if (index > -1) {
        following.value.splice(index, 1)
      }
    }
  } catch (error) {
    console.error('取消关注失败:', error)
  }
}

// 监听标签切换，重置页码
watch(activeTab, () => {
  currentPage.value = 1
})

// 监听搜索，重置页码
watch(searchQuery, () => {
  currentPage.value = 1
})

onMounted(async () => {
  loading.value = true
  await Promise.all([
    loadFollowing(),
    loadFollowers(),
    loadStats(),
    loadRecommendations()
  ])
  loading.value = false
})
</script>